package com.myapplication.zhou.fragment;


import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.google.gson.Gson;
import com.myapplication.adapter.ShopCartRecycleAdapter;
import com.myapplication.callback.ShopCartCallback;
import com.myapplication.helper.PreferencesHelper;
import com.myapplication.interfaces.ShopCartConnect;
import com.myapplication.itemdecoration.DividerItemDecoration;
import com.myapplication.model.CartInfo;
import com.myapplication.model.Store;
import com.myapplication.model.UserInfo;
import com.myapplication.zhou.alldemo.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShoppingCartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShoppingCartFragment extends Fragment implements ShopCartCallback,
        SwipeRefreshLayout.OnRefreshListener, ShopCartRecycleAdapter.CheckClick, ShopCartRecycleAdapter.CheckClickOnChild
        , ShopCartRecycleAdapter.JiaJianClick,View.OnClickListener {

    private ShopCartConnect shopCartConnect;
    @ViewInject(R.id.toolbar)
    private Toolbar toolbar;
    @ViewInject(R.id.textView_title)
    private TextView textView_title;
    @ViewInject(R.id.textView_bianji)
    private TextView textView_bianji;
    @ViewInject(R.id.recycleView)
    private RecyclerView recyclerView;
    @ViewInject(R.id.swipeRefresh)
    private SwipeRefreshLayout refreshLayout;
    private List<Store> stores = new ArrayList<>();
    private Gson gson;
    private ShopCartRecycleAdapter shopCartRecycleAdapter;
    private LinearLayoutManager layoutManager;
    @ViewInject(R.id.checkbox)
    private CheckBox checkBox;
    @ViewInject(R.id.textView_allPrice)
    private TextView textView_allPrice;

    public ShoppingCartFragment() {
        // Required empty public constructor
    }


    // TODO: Rename and change types and number of parameters
    public static ShoppingCartFragment newInstance() {
        ShoppingCartFragment fragment = new ShoppingCartFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    /*    goToLoginActivity(getSH());*/
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                onRefresh();
            }
        });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_shopping_cart, container, false);
        x.view().inject(this, view);
        gson = new Gson();
        refreshLayout.setColorSchemeResources(android.R.color.holo_orange_light, android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_red_light);
        refreshLayout.setOnRefreshListener(this);
        shopCartConnect = new ShopCartConnect();
        layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        shopCartRecycleAdapter = new ShopCartRecycleAdapter(getContext(), stores);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(shopCartRecycleAdapter);
        shopCartRecycleAdapter.addOnItemCheckClick(this);
        shopCartRecycleAdapter.jiajianClick(this);
        shopCartRecycleAdapter.addOnItemChildCheck(this);
        checkBox.setOnClickListener(this);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), R.drawable.divider));
        return view;
    }

    @Override
    public void onShopCartSuccess(String success) {
        stores.clear();
        refreshLayout.setRefreshing(false);
        Log.e(">>>>>>>success", success);
        paraseJsonForCart(success);

    }

    private void paraseJsonForCart(String success) {

        try {
            JSONObject jsonObject = new JSONObject(success);
            JSONObject jsonObject1 = jsonObject.optJSONObject("datas");
            JSONObject jsonObject2 = jsonObject1.optJSONObject("cart_list");
            Iterator<String> keys = jsonObject2.keys();
            List<String> list1 = new ArrayList<>();

            while (keys.hasNext()) {
                String key = keys.next();
                list1.add(key);
            }
            for (int i = 0; i < list1.size(); i++) {
                Store store = new Store();
                JSONObject jsonObject3 = jsonObject2.optJSONObject(list1.get(i));
                Iterator<String> keys2 = jsonObject3.keys();
                List<CartInfo> cartInfos = new ArrayList<>();
                while (keys2.hasNext()) {
                    String key = keys2.next();
                    if (key.equals("store_name")) {
                        String storename = jsonObject3.optString("store_name");
                        store.setStore(storename);
                        store.setChecked(false);
                    } else {
                        JSONObject jsonObject4 = jsonObject3.optJSONObject(key);

                        CartInfo cartInfo = gson.fromJson(jsonObject4.toString(), CartInfo.class);
                        cartInfo.setChecked(false);
                        cartInfos.add(cartInfo);
                    }
                }
                store.setList(cartInfos);
                stores.add(store);
            }
            shopCartRecycleAdapter.Update(stores);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onShopCartFail(String fail) {

    }

    @Override
    public void onRefresh() {
        //key 2088e1088a5a7a7ed05948e195160d3a
        refreshLayout.setRefreshing(true);
        Log.e("key", getSH().getKey());

        shopCartConnect.getShopCartInfo(getSH().getKey(), this);
    }

    public UserInfo getSH() {

        return PreferencesHelper.getUserInfo(getContext());
    }


    @Override
    public void onCheckClick(View v, Store store, int position) {
        String price = "0.0";
        if (v instanceof CheckBox && !store.getChecked()) {
            ((CheckBox) v).setChecked(true);
            store.setChecked(true);
            for (int i = 0; i < store.getList().size(); i++) {
                store.getList().get(i).setChecked(true);

            }
        } else if (v instanceof CheckBox && store.getChecked()) {
            ((CheckBox) v).setChecked(false);
            store.setChecked(false);
            for (int i = 0; i < store.getList().size(); i++) {
                store.getList().get(i).setChecked(false);
            }
        }



        updateRecyclerView(position);
        price = getPrice();
        textView_allPrice.setText(price);
    }


    @Override
    public void onChild(View v, CartInfo cartInfo, int postion, int listpostion) {
        String price = "0.0";
        if (v instanceof CheckBox && !cartInfo.isChecked()) {
            ((CheckBox) v).setChecked(true);
            stores.get(listpostion).getList().get(postion).setChecked(true);
        } else if (v instanceof CheckBox && cartInfo.isChecked()) {
            ((CheckBox) v).setChecked(false);
            stores.get(listpostion).getList().get(postion).setChecked(false);
        }
        boolean flag = false;
        for (int i = 0; i < stores.get(listpostion).getList().size(); i++) {
            if (!stores.get(listpostion).getList().get(i).isChecked()) {
                flag = false;
                break;
            } else {
                flag = true;
            }
        }
        stores.get(listpostion).setChecked(flag);
        updateRecyclerView(listpostion);
        price = getPrice();
        textView_allPrice.setText(price);
    }

    public void updateRecyclerView(int position) {
        int fristPos = layoutManager.findFirstVisibleItemPosition();
        int lastPos = layoutManager.findLastVisibleItemPosition();

        if (position >= fristPos && position <= lastPos) {
            View view = layoutManager.findViewByPosition(position);
            if (null != recyclerView.getChildViewHolder(view)) {
                ShopCartRecycleAdapter.CartViewHolder cartViewHolder = (ShopCartRecycleAdapter.CartViewHolder) recyclerView.getChildViewHolder(view);
                shopCartRecycleAdapter.update(position, cartViewHolder);
            }

        }
    }

    @Override
    public void jiajian(View v, CartInfo cartInfo, int postion,int listPosition) {
        String price = "0.0";
        switch (v.getId()){
            case R.id.textView_jia:
                int num = Integer.parseInt(cartInfo.getGoods_num());
                num=num+1;
                cartInfo.setGoods_num(num+"");
                double sum = Double.parseDouble(cartInfo.getGoods_price());
                cartInfo.setGoods_sum(num*sum+"");
                price = getPrice();
                textView_allPrice.setText(price);
                break;
            case R.id.textView_jian:
                int num1 = Integer.parseInt(cartInfo.getGoods_num());
                if(num1==1){
                    Snackbar snackbar = Snackbar.make(textView_bianji,"数量至少为1",Snackbar.LENGTH_SHORT);
                    snackbar.getView().setBackgroundColor(getResources().getColor(R.color.colorAccent));
                    snackbar.show();
                }else{
                    num1=num1-1;
                    cartInfo.setGoods_num(num1+"");
                    double sum1 = Double.parseDouble(cartInfo.getGoods_price());
                    cartInfo.setGoods_sum(num1*sum1+"");
                }

                price = getPrice();
                textView_allPrice.setText(price);
                break;
        }
        updateRecyclerView(listPosition);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.checkbox:
                String price = getPrice();
                if(checkBox.isChecked()) {

                    for (Store store : stores) {
                        store.setChecked(true);
                        for (CartInfo cartInfo : store.getList()) {
                            cartInfo.setChecked(true);
                           // price = price + Integer.parseInt(cartInfo.getGoods_num()) * Double.parseDouble(cartInfo.getGoods_price());
                        }
                    }

                    shopCartRecycleAdapter = new ShopCartRecycleAdapter(getContext(), stores);
                    recyclerView.setAdapter(shopCartRecycleAdapter);


                }else{
                    for (Store store : stores) {
                        store.setChecked(false);
                        for (CartInfo cartInfo : store.getList()) {
                            cartInfo.setChecked(false);
                            // price = price + Integer.parseInt(cartInfo.getGoods_num()) * Double.parseDouble(cartInfo.getGoods_price());
                        }
                    }
                    shopCartRecycleAdapter = new ShopCartRecycleAdapter(getContext(), stores);
                    recyclerView.setAdapter(shopCartRecycleAdapter);
                    textView_allPrice.setText(price);
                }

                shopCartRecycleAdapter.addOnItemCheckClick(this);
                shopCartRecycleAdapter.jiajianClick(this);
                shopCartRecycleAdapter.addOnItemChildCheck(this);
                checkBox.setOnClickListener(this);
                price  = getPrice();
                textView_allPrice.setText(price);

                break;
        }
    }


    public String getPrice(){
        double price = 0.0;
        for (Store store : stores) {
            for (CartInfo cartInfo : store.getList()) {
                if(cartInfo.isChecked())
                 price = price + Integer.parseInt(cartInfo.getGoods_num()) * Double.parseDouble(cartInfo.getGoods_price());
            }
        }
        return price+"";
    }

}
